package com.easyapi.server.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.easyapi.common.enums.StatusCode;
import com.easyapi.common.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;


/**
 * @author  druid 工具类
 */
public class DruidDataSourceUtil {
    private static final Logger log = LoggerFactory.getLogger(DruidDataSourceUtil.class);
    /**
     * 获取druid数据源
     * @param dataJson
     * @param username
     * @param password
     * @param driverClassName
     * @return
     */
    public static DruidDataSource getDruidDataSource(String dataJson, String username, String password, String driverClassName) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataJson);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName(driverClassName);
        //设置数据连接池相关属性
        druidDataSource.setConnectionErrorRetryAttempts(1);//失败重试1次
        druidDataSource.setInitialSize(5);//初始化连接数
        druidDataSource.setMinIdle(5);//最小空闲连接数
        druidDataSource.setMaxActive(20);//最大连接数
        druidDataSource.setMaxWait(60000);//最大等待时间
        druidDataSource.setTimeBetweenEvictionRunsMillis(6*60*1000);//连接回收时间
        druidDataSource.setMinEvictableIdleTimeMillis(5*60*1000);//连接在池中最小生存时间
        druidDataSource.setValidationQuery("SELECT 1");
        druidDataSource.setTestWhileIdle(true);
        try {
            druidDataSource.init();
            druidDataSource.getConnection();

        } catch (SQLException e) {
            log.error("link datasource error:{},dataJson:{},driverClassName:{},username:{}", e.getMessage(), dataJson, driverClassName, username);
            druidDataSource.close();
            return null;
        }
        log.error("link datasource success,dataJson:{},driverClassName:{},username:{}", dataJson, driverClassName, username);
        return druidDataSource;
    }

    public static void testDatasourceConnection(String json, String username, String password) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(json);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setInitialSize(5); // 初始化连接数
        druidDataSource.setConnectionErrorRetryAttempts(1);
        try {
            druidDataSource.init();
            druidDataSource.getConnection();
        } catch (SQLException e) {
            log.error("link datasource error:{}", e.getMessage());
            throw new BizException(StatusCode.LINK_DATASOURCE_FALSE);
        } finally {
            druidDataSource.close();
        }
    }
}
